Page({
  /**
   * 页面的初始数据
   */
  data: {
    postId: null,
    postData: {},
    commentList: [],
    showCommentInput: false,
    commentText: '',
    replyPlaceholder: '',
    currentCommentId: null,
    currentReplyId: null,
    currentReplyName: '',
    isOwnPost: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        postId: options.id
      });
      this.getPostDetail(options.id);
      this.getCommentList(options.id);
    }
  },

  /**
   * 获取帖子详情
   */
  getPostDetail: function (postId) {
    // 模拟请求，实际开发中应使用wx.request请求后端API
    const postData = this.getMockPostDetail(postId);
    this.setData({
      postData: postData,
      isOwnPost: postData.isOwnPost || false
    });
  },

  /**
   * 获取帖子评论列表
   */
  getCommentList: function (postId) {
    // 模拟请求，实际开发中应使用wx.request请求后端API
    const commentList = this.getMockCommentList(postId);
    this.setData({
      commentList: commentList
    });
  },

  /**
   * 模拟帖子详情数据
   */
  getMockPostDetail: function (postId) {
    // 返回模拟数据，实际应从服务器获取
    return {
      id: postId,
      author: '小红书用户',
      avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-0.png',
      publishTime: '10分钟前',
      isFollowed: false,
      title: '前端开发入门心得分享',
      content: '最近开始学习前端开发，感觉挺有意思的。HTML和CSS还比较简单，JavaScript就需要更多的时间去理解了。分享一些学习资源，希望对大家有帮助！',
      images: [
        'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/post-image1.png',
        'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/post-image2.png',
        'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/post-image3.png'
      ],
      location: '北京市海淀区',
      relatedContent: {
        type: '岗位',
        title: '前端开发工程师',
        desc: '负责公司产品的前端开发，要求熟悉HTML、CSS、JavaScript等技术',
        coverUrl: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/job-cover.png'
      },
      group: {
        name: '前端开发交流群',
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/group-avatar.png'
      },
      tags: ['前端开发', 'JavaScript', 'Vue.js', 'React', '学习资源'],
      watchCount: 238,
      collectCount: 42,
      commentCount: 15,
      shareCount: 7,
      likeCount: 56,
      isLiked: false,
      isCollected: false,
      isOwnPost: false
    };
  },

  /**
   * 模拟评论列表数据
   */
  getMockCommentList: function (postId) {
    // 返回模拟数据，实际应从服务器获取
    return [
      {
        id: 1,
        username: '前端爱好者',
        userid: 'user1',
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-1.png',
        content: '感谢分享，这些资源对我很有帮助！',
        time: '8分钟前',
        likeCount: 5,
        isLiked: false,
        replyCount: 2,
        replies: [
          {
            id: 101,
            username: '小红书用户',
            userid: 'post_author',
            content: '不客气，希望对你的学习有帮助~',
            time: '7分钟前',
            isLiked: false
          },
          {
            id: 102,
            username: 'Web开发者',
            userid: 'user3',
            replyTo: '小红书用户',
            content: '这些资源质量都很高，推荐大家看看',
            time: '5分钟前',
            isLiked: false
          }
        ]
      },
      {
        id: 2,
        username: '程序员小王',
        userid: 'user2',
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d928162-0.png',
        content: '前端框架那么多，建议先专注学习一个，等熟悉了再去尝试其他的。我个人比较推荐Vue.js作为入门框架，上手比较容易。',
        time: '6分钟前',
        likeCount: 3,
        isLiked: false,
        replyCount: 0,
        replies: []
      }
    ];
  },

  /**
   * 返回上一页
   */
  goBack: function () {
    wx.navigateBack();
  },

  /**
   * 显示更多操作菜单
   */
  showMoreActions: function () {
    wx.showActionSheet({
      itemList: ['举报', '收藏', '不感兴趣'],
      success: (res) => {
        const index = res.tapIndex;
        if (index === 0) {
          wx.showToast({
            title: '举报成功',
            icon: 'success'
          });
        } else if (index === 1) {
          this.toggleCollect();
        } else if (index === 2) {
          wx.showToast({
            title: '已减少此类内容推荐',
            icon: 'none'
          });
        }
      }
    });
  },

  /**
   * 查看用户资料
   */
  viewUserProfile: function (e) {
    const userid = e.currentTarget.dataset.userid || this.data.postData.userid;
    console.log('查看用户资料:', userid);
    // 实际开发中跳转到用户资料页
    wx.showToast({
      title: '查看用户资料: ' + userid,
      icon: 'none'
    });
  },

  /**
   * 关注/取消关注
   */
  toggleFollow: function () {
    const isFollowed = !this.data.postData.isFollowed;
    this.setData({
      'postData.isFollowed': isFollowed
    });
    
    wx.showToast({
      title: isFollowed ? '已关注' : '已取消关注',
      icon: 'success'
    });
  },

  /**
   * 预览图片
   */
  previewImage: function (e) {
    const src = e.currentTarget.dataset.src;
    const images = this.data.postData.images;
    
    wx.previewImage({
      current: src,
      urls: images
    });
  },

  /**
   * 查看位置
   */
  viewLocation: function () {
    const location = this.data.postData.location;
    
    wx.showToast({
      title: '查看位置: ' + location,
      icon: 'none'
    });
    
    // 实际开发中可以跳转到地图页面
  },

  /**
   * 查看群聊
   */
  viewGroup: function () {
    const group = this.data.postData.group;
    
    wx.showToast({
      title: '进入群聊: ' + group.name,
      icon: 'none'
    });
    
    // 实际开发中可以跳转到群聊页面
  },

  /**
   * 搜索标签
   */
  searchTag: function (e) {
    const tag = e.currentTarget.dataset.tag;
    
    wx.showToast({
      title: '搜索标签: ' + tag,
      icon: 'none'
    });
    
    // 实际开发中可以跳转到标签搜索结果页
  },

  /**
   * 点赞/取消点赞
   */
  toggleLike: function () {
    const isLiked = !this.data.postData.isLiked;
    const likeCount = isLiked 
      ? this.data.postData.likeCount + 1 
      : this.data.postData.likeCount - 1;
    
    this.setData({
      'postData.isLiked': isLiked,
      'postData.likeCount': likeCount
    });
    
    wx.showToast({
      title: isLiked ? '已点赞' : '已取消点赞',
      icon: 'success'
    });
  },

  /**
   * 收藏/取消收藏
   */
  toggleCollect: function () {
    const isCollected = !this.data.postData.isCollected;
    const collectCount = isCollected 
      ? this.data.postData.collectCount + 1 
      : this.data.postData.collectCount - 1;
    
    this.setData({
      'postData.isCollected': isCollected,
      'postData.collectCount': collectCount
    });
    
    wx.showToast({
      title: isCollected ? '已收藏' : '已取消收藏',
      icon: 'success'
    });
  },

  /**
   * 分享帖子
   */
  sharePost: function () {
    const shareCount = this.data.postData.shareCount + 1;
    
    this.setData({
      'postData.shareCount': shareCount
    });
    
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  /**
   * 点赞评论
   */
  likeComment: function (e) {
    const index = e.currentTarget.dataset.index;
    const isLiked = !this.data.commentList[index].isLiked;
    const likeCount = isLiked 
      ? this.data.commentList[index].likeCount + 1 
      : this.data.commentList[index].likeCount - 1;
    
    this.setData({
      [`commentList[${index}].isLiked`]: isLiked,
      [`commentList[${index}].likeCount`]: likeCount
    });
  },

  /**
   * 回复评论
   */
  replyComment: function (e) {
    const index = e.currentTarget.dataset.index;
    const comment = this.data.commentList[index];
    
    this.setData({
      showCommentInput: true,
      replyPlaceholder: `回复 @${comment.username}：`,
      currentCommentId: comment.id,
      currentReplyId: null,
      currentReplyName: comment.username,
      commentText: ''
    });
  },

  /**
   * 回复子评论
   */
  replyToComment: function (e) {
    const pid = e.currentTarget.dataset.pid; // 父评论ID
    const rid = e.currentTarget.dataset.rid; // 回复ID
    const name = e.currentTarget.dataset.name; // 回复人用户名
    
    this.setData({
      showCommentInput: true,
      replyPlaceholder: `回复 @${name}：`,
      currentCommentId: pid,
      currentReplyId: rid,
      currentReplyName: name,
      commentText: ''
    });
  },

  /**
   * 查看全部回复
   */
  viewAllReplies: function (e) {
    const commentId = e.currentTarget.dataset.id;
    
    wx.showToast({
      title: '查看全部回复功能待开发',
      icon: 'none'
    });
    
    // 实际开发中可以跳转到评论详情页或加载更多回复
  },

  /**
   * 聚焦评论输入框
   */
  focusCommentInput: function () {
    this.setData({
      showCommentInput: true,
      replyPlaceholder: '说点什么...',
      currentCommentId: null,
      currentReplyId: null,
      currentReplyName: '',
      commentText: ''
    });
  },

  /**
   * 隐藏评论输入框
   */
  hideCommentInput: function () {
    this.setData({
      showCommentInput: false
    });
  },

  /**
   * 评论输入变化
   */
  onCommentInput: function (e) {
    this.setData({
      commentText: e.detail.value
    });
  },

  /**
   * 提交评论
   */
  submitComment: function () {
    const content = this.data.commentText.trim();
    
    if (!content) {
      wx.showToast({
        title: '评论内容不能为空',
        icon: 'none'
      });
      return;
    }
    
    // 是回复评论
    if (this.data.currentCommentId) {
      this.submitReply(content);
    } else {
      // 是新评论
      this.submitNewComment(content);
    }
    
    this.setData({
      showCommentInput: false,
      commentText: ''
    });
  },
  
  /**
   * 提交新评论
   */
  submitNewComment: function (content) {
    // 模拟新评论数据
    const newComment = {
      id: Date.now(),
      username: '当前用户',
      userid: 'current_user',
      avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d928162-1.png',
      content: content,
      time: '刚刚',
      likeCount: 0,
      isLiked: false,
      replyCount: 0,
      replies: []
    };
    
    // 更新评论列表和评论数量
    const commentList = [newComment, ...this.data.commentList];
    const commentCount = this.data.postData.commentCount + 1;
    
    this.setData({
      commentList: commentList,
      'postData.commentCount': commentCount
    });
    
    wx.showToast({
      title: '评论成功',
      icon: 'success'
    });
  },
  
  /**
   * 提交回复
   */
  submitReply: function (content) {
    // 查找要回复的评论
    const commentIndex = this.data.commentList.findIndex(
      item => item.id === this.data.currentCommentId
    );
    
    if (commentIndex === -1) return;
    
    // 模拟回复数据
    const newReply = {
      id: Date.now(),
      username: '当前用户',
      userid: 'current_user',
      content: content,
      time: '刚刚',
      isLiked: false
    };
    
    // 如果是回复别人的回复，添加replyTo字段
    if (this.data.currentReplyId) {
      newReply.replyTo = this.data.currentReplyName;
    }
    
    // 更新回复列表和回复数量
    let replies = [...this.data.commentList[commentIndex].replies];
    replies.push(newReply);
    
    const replyCount = this.data.commentList[commentIndex].replyCount + 1;
    
    this.setData({
      [`commentList[${commentIndex}].replies`]: replies,
      [`commentList[${commentIndex}].replyCount`]: replyCount
    });
    
    wx.showToast({
      title: '回复成功',
      icon: 'success'
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const postData = this.data.postData;
    return {
      title: postData.title || '分享一个帖子',
      path: `/pages/post-detail/post-detail?id=${postData.id}`,
      imageUrl: postData.images && postData.images.length > 0 ? postData.images[0] : ''
    };
  }
}) 